import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'
import Dashboard from '../views/Dashboard.vue'
import UserManagement from '../views/UserManagement.vue'
import PermissionManagement from '../views/PermissionManagement.vue'
import Settings from '../views/Settings.vue'
import Login from '../views/Login.vue'
import ApiTest from '../views/ApiTest.vue'
import AvatarDemo from '../views/AvatarDemo.vue'
import AvatarTest from '../views/AvatarTest.vue'
import Developing from '../views/Developing.vue'
import RoleManagement from '../views/RoleManagement.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/api-test',
    component: ApiTest,
    meta: { title: 'API测试' }
  },
  {
    path: '/avatar-demo',
    component: AvatarDemo,
    meta: { title: '头像功能演示' }
  },
  {
    path: '/avatar-test',
    component: AvatarTest,
    meta: { title: '头像功能测试' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard, meta: { title: '仪表盘' } },
      { path: 'user', component: UserManagement, meta: { title: '用户管理' } },
      { path: 'settings', component: Settings, meta: { title: '系统设置' } },
      { path: 'role', component: RoleManagement, meta: { title: '角色管理' } },
      { path: 'permission', component: PermissionManagement, meta: { title: '权限管理' } },
      { path: 'menu', component: Developing, meta: { title: '菜单管理' } },
      { path: 'log', component: Developing, meta: { title: '日志管理' } },
      { path: 'terminal', component: Developing, meta: { title: '权限终端' } },
      { path: 'test', component: Developing, meta: { title: '权限测试页' } }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

function isTokenExpired(token) {
  // 只要有token就认为未过期
  return !token;
}

// 登录守卫
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin')
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && to.path !== '/api-test' && to.path !== '/avatar-demo' && to.path !== '/avatar-test') {
    if (!isLogin || !token || isTokenExpired(token)) {
      if (!window.__hasShownLoginExpired) {
        window.__hasShownLoginExpired = true
        ElMessage({
          message: '登录已过期，请重新登录',
          type: 'warning',
          duration: 2000,
          onClose: () => {
            window.__hasShownLoginExpired = false
            localStorage.removeItem('token')
            localStorage.removeItem('username')
            localStorage.removeItem('isLogin')
            next('/login')
          }
        })
      }
    } else {
      next()
    }
  } else if (to.path === '/login' && isLogin && token && !isTokenExpired(token)) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
